﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using OConf.NetCore.Common;
using OConf.NetCore.Model;
using OConf.NetCore.Options;
using OConf.NetCore.SignalR;
using OConf.NetCore.Static;

namespace OConf.NetCore
{
    /// <summary>
    /// 定时任务
    /// </summary>
    public class ConfigJob : BackgroundService
    {
        private readonly string _secretKey;
        private readonly string _server;
        private readonly string _programName;
        private readonly IConfiguration _configuration;
        public ConfigJob(IConfiguration configuration)
        {
            _configuration = configuration;
            _server = _configuration["OConf:Server"];
            _programName = _configuration["OConf:ProgramName"];
            _secretKey = _configuration["OConf:SecretKey"];

            if (string.IsNullOrEmpty(_server) || string.IsNullOrEmpty(_programName))
            {
                throw new ArgumentException("ServerIP or ProgramName IsNullOrEmpty");
            }
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            if (!ConfigLoadingOptions.IsRTC)
            {
                return;
            }

            //初始化SignalR长连接
            SignalRClient.InitConfigClient(_server, _programName, _secretKey);

            Task.Run(async () =>
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    await Task.Delay(TimeSpan.FromMinutes(5));
                    CheckConfigInfo();
                }
            });
        }

        /// <summary>
        /// 检查配置信息是否需要更新
        /// </summary>
        private void CheckConfigInfo()
        {
            FileCore.CreateDirectory(Cache.saveDicPath);
            string url = _server.TrimEnd('/') + "/api/ConfigBackEnd/V2/CheckConfigInfo";

            var loadedNameSpaces = ConfigNameSpaceOptions.GetNameSpace();
            //没有指定要加载的空间
            if (loadedNameSpaces.Count <= 0)
            {
                return;
            }

            ProjectConfigModel projectConfig = Cache.GetProjectConfig();
            if (projectConfig == null)
            {
                //项目配置信息不存在，需要从服务端重新获取全部的配置信息
                projectConfig = new ProjectConfigModel()
                {
                    LastPublishTime = 0
                };
            }

            #region 从服务端获取配置信息
            SortedDictionary<string, object> requestParam = new SortedDictionary<string, object>();
            requestParam.Add("ProgramName", _programName);
            requestParam.Add("LastPublishTime", projectConfig.LastPublishTime);
            requestParam.Add("NameSpaces", loadedNameSpaces);
            requestParam.Add("Key", _secretKey);
            string sign = JsonConvert.SerializeObject(requestParam).MD5Encrypt32();
            requestParam.Add("Sign", sign);

            string resJson = HttpRequestUnit.PostAsync(url, requestParam, timeout: 10).Result;
            ReturnData<BackProgramConfigInfo> result = JsonConvert.DeserializeObject<ReturnData<BackProgramConfigInfo>>(resJson);
            if (result == null)
            {
                return;
            }
            if (result.Code == (int)StatusCode.配置信息已是最新)
            {
                return;
            }
            if (result.Code != (int)StatusCode.服务器成功返回请求数据)
            {
                return;
            }

            //保存配置信息
            ConfigCommon.SaveConfigInfo(result.Data);
            #endregion
        }
    }
}
